/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "lm75.h"
#include <mc/exception.h>

using namespace dev;

bool chip_lm75::init(mc::mutable_dict& csr_object) {
    try {
        // 调用chip_base的init函数
        chip_base::init(csr_object);
    } catch (const std::exception& e) {
        elog("LM75 configuration loading failed: ${error}", ("error", e.what()));
        return false;
    }

    return true;
}

int32_t chip_lm75::chip_test(uint32_t* result) {
    try {
        std::vector<uint8_t> buffer      = {0x55, 0x00};
        std::vector<uint8_t> read_buffer = {0x00, 0x00};
        std::string error;
        int32_t             ret         = block_write(0, buffer, read_buffer, error);
        if (ret != HAS_OK) {
            return HAS_ERR;
        }
        ret = block_read(0, 2, buffer, read_buffer, error);
        if (ret != HAS_OK) {
            return HAS_ERR;
        }
        if (read_buffer[0] != buffer[0] || read_buffer[1] != buffer[1]) {
            return HAS_ERR;
        }
        return HAS_OK;
    } catch (const std::exception& e) {
        elog("LM75 self-test failed: ${error}", ("error", e.what()));
        return HAS_ERR;
    }
}

int32_t chip_lm75::block_read(uint32_t offset, uint32_t length, std::vector<uint8_t>& empty_buffer,
                               std::vector<uint8_t>& buffer, std::string& error) {
    try {
        if (length != 2 && length != 1) {
            error = "LM75 read length error";
            MC_THROW(mc::invalid_op_exception, error);
        }
        // 调用基类的block_read方法
        return chip_base::block_read(offset, length, empty_buffer, buffer, error);
    } catch (const std::exception& e) {
        error = std::string("LM75 read failed: ") + e.what();
        elog("${error}", ("error", error));
        return HAS_ERR;
    }
}
